package com.northpool.operator.common.file;

import cn.hutool.core.io.FileUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.exception.ParamException;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

import java.io.File;

@OperatorInfo(ref = "FileRenameOperator", name = "文件重命名", version = "1.0.0")
public class FileRenameOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "oldPath", name = "旧文件路径", desc = "旧文件路径，如：/data/temp.txt", required = true),
            @InputParam(ref = "newFileName", name = "新文件名称", desc = "新文件名称, 如：temp_new.txt", required = true),
            @InputParam(ref = "isOverride", name = "是否覆盖", desc = "如果目标文件已存在，是否覆盖", type = TypeEnum.BOOL, value =  "false"),
    })
    public FileRenameOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(FileRenameOperator.class, TestParamBuilder.aBuilder()
                .param("oldPath", "d:/temp/stp-jianmu")
                .param("newFileName", "stp-jianmu-new")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String oldPath = paramTool.getStr("oldPath");
        String newFileName = paramTool.getStr("newFileName");
        Boolean isOverride = paramTool.getBool("isOverride");

        File file = FileUtil.file(oldPath);
        if (!file.exists()) {
            throw new ParamException("oldPath", "文件不存在");
        }
        FileUtil.rename(file, newFileName, isOverride);
        this.log("文件重命名成功：{}", newFileName);
    }
}
